<?php

namespace App\Model;

use App\Common\Constant;
use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

/**
 * Class InterPushMatchUser
 *
 * @package App\Model
 * @mixin \Eloquent
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\InterPushMatchUser newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\InterPushMatchUser newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\InterPushMatchUser query()
 * @property int $id
 * @property int $user_id 主动：用户id
 * @property int $share 主动：1分享，0微分享
 * @property string|null $share_time 主动：分享时间
 * @property string|null $province 主动：帮我推_省
 * @property string|null $hutui_article 主动：默认推广的个人网页
 * @property int $interpush_type 主动：推广类型1个人网页，2文章
 * @property int $match_user_id 被动：匹配到用户id
 * @property int $match_share 被动：1分享，0微分享
 * @property string|null $match_share_time 被动：分享时间
 * @property string|null $match_province 被动：帮我推_省
 * @property int $match_interpush_type 被动：推广类型1个人网页，2文章
 * @property string|null $match_interpush_article 被动：默认推广的个人网页
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @property string|null $deleted_at
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\InterPushMatchUser whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\InterPushMatchUser whereDeletedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\InterPushMatchUser whereHutuiArticle($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\InterPushMatchUser whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\InterPushMatchUser whereInterpushType($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\InterPushMatchUser whereMatchInterpushArticle($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\InterPushMatchUser whereMatchInterpushType($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\InterPushMatchUser whereMatchProvince($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\InterPushMatchUser whereMatchShare($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\InterPushMatchUser whereMatchShareTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\InterPushMatchUser whereMatchUserId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\InterPushMatchUser whereProvince($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\InterPushMatchUser whereShare($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\InterPushMatchUser whereShareTime($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\InterPushMatchUser whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Model\InterPushMatchUser whereUserId($value)
 */
class InterPushMatchUser extends Model
{
    protected $table = 'interpush_match_user';

    protected $fillable = ['user_id', 'share', 'share_time', 'province', 'hutui_article', 'interpush_type', 'match_user_id', 'match_share', 'match_share_time', 'match_province', 'match_interpush_type', 'match_interpush_article'];


    public function add($data)
    {
        $this->user_id = $data['user_id'];
        $this->province = $data['province'];
        $this->interpush_type = $data['interpush_type'];
        $this->hutui_article = $data['hutui_article'];
        $this->match_user_id = $data['match_user_id'];
        $this->match_province = $data['match_province'];
        $this->match_interpush_type = $data['match_interpush_type'];
        $this->match_interpush_article = $data['match_interpush_article'];
        $this->save();
        return $this;
    }

    /**
     * 匹配新增用户
     * @param User $user
     * @return array|bool
     * @throws \Exception
     */
    public function addMatch(User $user)
    {
        $data = [];
        try {
            \DB::beginTransaction();
            $push_user_info = \DB::select("select * from interpush_user_info where user_id = ? for update", [$user->id]);
            $result = $this->getInterPushMatchUser($user->id);

            if ($result == Constant::INTER_PUSH_INFO_NUM) {
                \DB::commit();
                return 3;
            }
            // 用户从新 获取互推信息
            $res_user_info = $this->getRedisMatchUser($user->id, $push_user_info[0]->he_province_id);
            // 用户从新 获取互推信息
            if ($res_user_info) {
                $data = [
                    'user_id' => $push_user_info[0]->user_id,
                    'province' => $push_user_info[0]->me_province,
                    'interpush_type' => $push_user_info[0]->interpush_type,
                    'hutui_article' => $push_user_info[0]->interpush_article,
                    'match_user_id' => $res_user_info['user_id'],
                    'match_province' => $res_user_info['me_province'],
                    'match_interpush_type' => $res_user_info['interpush_type'],
                    'match_interpush_article' => $res_user_info['interpush_article']
                ];
                $res = $this->add($data);
                $inter_push_match_user_info[] = [
                    'id' => $res->id,
                    'match_user_id' => $res_user_info['user_id'],
                    'interpush_type' => $res_user_info['interpush_type'],
                    'interpush_article' => $res_user_info['interpush_article'],
                    'is_share' => 0,
                    'created_at' => $res->created_at
                ];
            } else {
                $inter_push_match_user_info = 0;
            }
            \DB::commit();

            return $inter_push_match_user_info;
        } catch (\Exception $exception) {
            \DB::rollBack();

            return '';

        }
    }


    /**
     * 递归配有效的用户
     * @param $user_id
     * @param $he_province_id
     * @return InterPushMatchUser|bool|Model|null|string
     */
    public function getRedisMatchUser($user_id, $he_province_id)
    {
        $arr = '';
        $i = 1;
        while (3) {
            if ($i > 3) break;
            // 1 首先从redis拿取一个数据
            $id = $this->getRedisSpop($he_province_id);
            if (!$id) return '';
            // 2 如果拿到数据就判断是不是跟本地用户相同，因为redis的数据不能等于当前用户自己
            if ($arr = $this->matchUserAndRedisUserInfo($user_id, $id, $he_province_id)) {
                break;
            }
            $arr = '';
            $i++;
        }
        return $arr;
    }

    /**
     * 通过redis数据匹配数据库是否相同的用户
     * @param $user_id
     * @param $id
     * @param $he_province_id
     * @return bool|Model|null|static
     */
    public function matchUserAndRedisUserInfo($user_id, $id, $he_province_id)
    {
        $bool =  $this->userInterPushInfo($user_id);
        if ($bool == false){
            return $this->redisPush($id, $he_province_id);
            }
        //通过redis 匹配出来的id
        //todo 没有开启互推圈也不能匹配
        $interPushUserInfo = InterPushUserInfo::where('id', $id)->first();
        if (!$interPushUserInfo->weixin_img || $interPushUserInfo->is_enabled == 2) {
            return $this->redisPush($id, $he_province_id);
        }

        //todo  匹配用户没有个人网页不能

        $item = DB::table("personal_page_template_user")->where("user_id", $interPushUserInfo->user_id)->where("is_default", 1)->first();
        $item1 = DB::table("personal_page_template_user")->where("user_id", $interPushUserInfo->user_id)->orderBy("created_at", "asc")->limit(1)->get();
        if ($item) {
            $template_id = $item->id;
        } else {
            if ($item1) {
                $template_id = $item[0]->id;
            } else {
                return $this->redisPush($id, $he_province_id);
            }
        }

        //todo  && ($interPushUserInfo->interpush_article == 0 || $interPushUserInfo->interpush_article == 1)
        if ($interPushUserInfo->interpush_type == 1) {

            $interPushUserInfo->interpush_article = $template_id;
            $interPushUserInfo->save();
        }
        //todo 个人基础信息
        if (!Cards::where("user_id", $interPushUserInfo->user_id)->first()) {

            return $this->redisPush($id, $he_province_id);
        }
        // todo 是否已经匹配 未分享
        $interPushMatchUser = InterPushMatchUser::where(['user_id' => $user_id, 'match_user_id' => $interPushUserInfo->user_id, 'share' => 0])->first();
        $interPushMatchUserWhere = InterPushMatchUser::where(['user_id' => $user_id, 'match_user_id' => $interPushUserInfo->user_id, 'share' => 1])->where("created_at", 'like', '%' . date("Y-m-d") . "%")->first();
        // todo 被匹配未分享
        $matchUser = InterPushMatchUser::where(['match_user_id' => $interPushUserInfo->user_id, 'match_share' => 0])->count();
        if ($interPushMatchUser || $matchUser > 3 || $interPushMatchUserWhere) {

            return $this->redisPush($id, $he_province_id);
        }

        if ($interPushUserInfo->user_id != $user_id) { // 如果匹配到了就放回匹配到的用户数据

            if ($interPushUserInfo->me_province_id == $he_province_id) {
                return $interPushUserInfo;
            } else {

                return $this->redisPush($id, $he_province_id);
            }
        } else { // 如果没匹配到就返回false，并且将本人的id写入redis队列，让其他人匹配到自己

            return $this->redisPush($id, $he_province_id);
        }
    }

    public function redisPush($id, $he_province_id)
    {
        $name1 = date('Ymd') . '_' . $he_province_id . '_' . 'match_user';
        $redis = Redis::connection();
        $redis->rpush($name1, $id);
        return false;
    }

    public function userInterPushInfo($user_id)
    {
        $interPushUserInfo = InterPushUserInfo::where('user_id', $user_id)->first();
        if ($interPushUserInfo->interpush_type == 1) {
            $item = DB::table("personal_page_template_user")->where("user_id", $user_id)->where("is_default", 1)->first();
            $item1 = DB::table("personal_page_template_user")->where("user_id", $user_id)->orderBy("created_at", "asc")->limit(1)->get();

            if ($item) {
                $template_id = $item->id;
            } else {
                if ($item1) {
                    $template_id = $item[0]->id;
                }else{
                    return false;
                }
            }
            $interPushUserInfo->interpush_article = $template_id;
            $interPushUserInfo->save();
        }
        return true;
    }

    /**
     * 获取redis中用户被匹配的id
     * @return string
     */
    public function getRedisSpop($he_province_id)
    {
        $name1 = date('Ymd') . '_' . $he_province_id . '_' . 'match_user';
        $redis = Redis::connection();
        $id = $redis->lpop($name1);
        return $id;
    }

    public function getInterPushMatchUser($user_id)
    {
        $res = \DB::selectOne('SELECT COUNT(id) as num  FROM interpush_match_user WHERE user_id =  ?  and  created_at LIKE ?', [$user_id, '%' . date('Y-m-d') . '%']);
        return $res->num;
    }


}
